milena.service = {}
milena.exit = {}
milena.menu = {}
milena.startdir = milena.startdir:gsub('\\', '/')
milena.dir = milena.startdir

package.path = '.\\?.mmod;.\\modules\\?.mmod;'..milena.directory..'\\modules\\?.mmod;'..package.path
package.cpath = package.cpath..";.\\?.dll;.\\?.so;..\\lib\\?.so;"..milena.directory..'\\?.dll;'..milena.directory..'\\libs\\?.ml;'..milena.directory..'\\libs\\?.dll;'

function milena.service.error_msg(...)
	local function normal(s)
		return s:gsub('<', '&lt;'):gsub('>', '&gt;'):gsub('\9', ('&nbsp;'):rep(8))
	end

	local traceback = debug.traceback(...)

	local lines = {}

	for l in traceback:gmatch('[^\n]+') do
		table.insert(lines, l)
	end
	local line = tonumber((lines[1]:gsub('(.+)%:([0-9]+).+', '%2')))
	local file = lines[1]:gsub('(.+)(%:[0-9]+).+', '%1'):gsub('(%.%w+)%.%w+', '%1')
	local room
	local loc
	for i, v in ipairs(milena.files) do
		if v.name==file then
			for i = line, 1, -1 do
				if string.char(string.byte(v.lines[i], 1)) == ':' then
					loc = v.lines[i]
					room = normal(v.index[loc].room):gsub('\n', '<br>')
					break
				end
			end
			break
		end
	end

	if room and loc then
		room = '<hr><div style="width:*; height: 2*; overflow: scroll;"><font color=blue>'..loc..'</font><br>'..room..'<font color=blue>endl</font></div>'
	end

	local function clines(l, st)
		local result = ''
		for i, v in ipairs(l) do
			v = normal(v):gsub('(%.%w+)%.%w+', '%1')
			if st then
				if i==1 then
					v = '<font color = red>'..v..'</font>'
				else
					v = '<font color = blue>'..v..'</font>'
				end
			end
			result = result..v..'<br>'
		end
		return result
	end
	milena.print('<html><body style="background-color: white; margin: 32px;"></body></html>')
	element.get('body'):set_html('<font size=2>'..'<br>'..clines(lines, true)..'</font>'..(room or ''), 0)
end

function milena.service.execute(f, ...)
	local args = {...}
	local result = {xpcall(function () return f(unpack(args)) end, milena.service.error_msg)}
	if result[1] then
		table.remove(result, 1)
		return unpack(result)
	end
	return nil, result[2]
end

dofile("include/other.lua")
require "lfs"
require "include.config"
config.load()

milena.service.execute(dofile, "include/main.lua")
